#include "../includes.h"

#include "OCXOAging.h"




char odetic_debug = 0;
char tod_debug = 0;
char time_debug = 0;
char ocxo_debug = 0;

#define lsiMessageOut(msg);   TransmitMessage((BYTE*)MESG,DEBUG_PORT);


int bLsiMonitorEnable;
int iLsiDebugVariable;
int iLsiClrBitCount;


typedef struct {
   unsigned errnum;
   char errmess[252];
} __rt_error;

typedef struct {
  int r[16];
} __rt_registers;


unsigned int fp_err_flag = 0;



void OutputTDAC()
{
	if( OCXO_ID.mode == ID_MODE_CURRENT ){

	   sprintf((char*)MESG,
	   "Temperature: Running Time: %8d"
	   " T:%5.2f ; C:%5.2f ; TDAC:%5.2f ; %d ; %s\r\n",
	   GC.RunningTime,
	   TEMPERATURE.CURRENT,TEMPERATURE.current,OCXO_ID.TDAC,GC.ACCsecond,OCXO_ID.id_str );

	}
	else{
	   sprintf((char*)MESG,
	   "Current: Running Time: %8d"
	   " T:%5.2f ; C:%5.2f ; TDAC:%5.2f ; %d ; %s\r\n",
	   GC.RunningTime,
	   TEMPERATURE.CURRENT,TEMPERATURE.current,OCXO_ID.TDAC,GC.ACCsecond,OCXO_ID.id_str );
	}

	TransmitMessage ((BYTE *) MESG, DEBUG_PORT);

}


float fCurrent,fTemp,fTDAC;
int findex;
char idtable = 1;
void DisplayIDTable()
{
	int i;
	int cnt;
	
	cnt = 0;
	idtable++;


	if( OCXO_ID.Valid == NO || CONFIG.TEMPER_CONTROL == NO ) {
		idtable = 0;
		return;
	}

	do{
		if(++cnt>20) return;
			
		fCurrent = fCurrent + (float)0.005;
		fTemp += (float)1.0;

		if( OCXO_ID.mode == ID_MODE_DAC ){

			if( fTemp < fIDTable[0].Temperature ) {
				findex = 0;
			}
			else if ( fTemp >= fIDTable[IDTable.TableNo-1].Temperature ) {
				findex = IDTable.TableNo-1;
			}
			else {
		   		for( i = 0; i < IDTable.TableNo-1; i++ ) {
		   			if( (fIDTable[i].Temperature <= fTemp ) && ( fTemp < fIDTable[i+1].Temperature) ){
						findex = i;
					}
				}
			}
		}
		else if(OCXO_ID.mode == ID_MODE_CURRENT ){

			if( fCurrent  < fIDTable[0].Temperature ) {
				findex = 0;
			}
			else if ( fCurrent  >= fIDTable[IDTable.TableNo-1].Temperature ) {
				findex = IDTable.TableNo-1;
			}
			else {
		   		for( i = 0; i < IDTable.TableNo-1; i++ ) {
		   			if( (fIDTable[i].Temperature <= fCurrent  ) && ( fCurrent  < fIDTable[i+1].Temperature) ){
						findex = i;
					}
				}
			}
		}

		
		if( OCXO_ID.mode == ID_MODE_FREQ ){
	   		fTDAC = -(fIDTable[findex].Yintercept + fIDTable[findex].Slope * (double)fTemp)/KGainF;
	   		
	    	printf(
	    			"FREQ_ID;index;%3d; "
	    			"T;%.3e;%.3e  \r\n",
	    			findex,
	    		(double)fTemp,(double)fTDAC );
	    	
	    	if(fTemp > 85 ) {
	    		idtable = 0;
	    		break;
	    	}
	   	}
		else if( OCXO_ID.mode == ID_MODE_DAC ){
	   		fTDAC = (fIDTable[findex].Yintercept + fIDTable[findex].Slope * (double)fTemp);

	    	printf(
	    			"TEMP-DAC ID;index;%3d; "
	    			"T;%.3e;%.3e\r\n",
	    			findex,
	    			(double)fTemp,(double)fTDAC );
	    		
	    	if(fTemp > 95 ) {
	    		idtable = 0;
	    		break;
	    	}
		}
		else if( OCXO_ID.mode == ID_MODE_CURRENT ){
	   		fTDAC = OCXO_ID.TDAC = (fIDTable[findex].Yintercept + fIDTable[findex].Slope * (double)fCurrent);
	    	
	    	printf(
	    			"CID;index;%3d; "
	    			"C;%.3e;%.3e  \r\n",
	    			findex,
	    			(double)fCurrent,(double)fTDAC );
	    	
	    	if(fCurrent > 0.5 ) {
	    		idtable = 0;
	    		break;
	    	}
	   	}
	}while(1);

}


void InitDual ()
{
  //Set All Signal Deactivated
  //Block Allow Allow Event
  bLsiMonitorEnable = 0;
  iLsiDebugVariable = 0;
  iLsiClrBitCount = 0;
  //Check Status
  //
/*
	MonitorADC();
	MonitorPlus5V();
	MonitorPlusVcc();
	MonitorMinusVee();
	MonitorVCXOEfc();
*/
}



int lsiPrevTEMP_RAW_DIGITS;
int lsiTEMP_RAW_DIGITS;
int lsiTEMP_RAW_DIGITS1;
int lsiTEMP_TRACE_RAW_DIGITS;

void ReadCounter()
{
    unsigned short Char1, Char2, Char3, Char4, skew;
    unsigned short usSC[2];
    int RefCount[3];

    lsiTEMP_RAW_DIGITS = ReadMainCounterAll();
    lsiTEMP_RAW_DIGITS1 = ReadMainCounter();

	lsiTEMP_TRACE_RAW_DIGITS = ReadTraceCounterFPGA();
/*
	sprintf((char*)MESG,
	"main,%09d,trace,%09d,adc,%03d,"
	"%02d,%02d,%02d,Synth,%08d,dly:%d,retry:%d,DIAG.ESYNC:%d,OP:%d"
	"\r\n",
	lsiTEMP_RAW_DIGITS,lsiTEMP_TRACE_RAW_DIGITS,usADCDetail,
	SYSTEM.TIME.CUR.HOUR, SYSTEM.TIME.CUR.MINUTE, SYSTEM.TIME.CUR.SECOND , 
	ReadSynthCounter()+esync_debug, iCntEvenSyncDly, sync_retry, DIAG.ESYNC, SYSTEM.OPERATION.STATUS);
*/
	
	sprintf((char*)MESG,
	"main,%09d,trace,%09d,detail_cnt,%3d,detail,%3.4lf,"
	"%02d,%02d,%02d,Synth,%08d,dly:%d,retry:%d,DIAG.ESYNC:%d,OP:%d"
	"\r\n",
	lsiTEMP_RAW_DIGITS,lsiTEMP_TRACE_RAW_DIGITS,detail_cnt,g_detail,
	SYSTEM.TIME.CUR.HOUR, SYSTEM.TIME.CUR.MINUTE, SYSTEM.TIME.CUR.SECOND , 
	ReadSynthCounter()+esync_debug, iCntEvenSyncDly, sync_retry, DIAG.ESYNC, SYSTEM.OPERATION.STATUS);	


	TransmitMessage((BYTE*)MESG,DEBUG_PORT);
    //MessageOut(MESG);
    lsiPrevTEMP_RAW_DIGITS=lsiTEMP_RAW_DIGITS;

   sprintf((char*)MESG,	">>GetCounterx(4) : %9d\n"
		   	   	   	"(0) : %02x, (1) : %02x, (2) : %02x, (3) : %02x, "
		   	   	 	 	"(4) : %02x, (5) : %02x, (6) : %02x, (7) : %02x, ",
		   	   	 	 	GetCounterx(4),
		   	   	 	 	GetFpgaValue(0),GetFpgaValue(1),GetFpgaValue(2),GetFpgaValue(3),
		   	   	 	 	GetFpgaValue(4),GetFpgaValue(5),GetFpgaValue(6),GetFpgaValue(7));

	TransmitMessage((BYTE*)MESG,DEBUG_PORT);
	Print_FPGAAddr();
	Print_FPGAData();

	//sprintf((char*)MESG,"S:%d,0x%02X,0x%02X,0x%02X,0x%02X\r\n",	ReadSynthCounter(),CS2addr[12],CS2addr[11],CS2addr[10],CS2addr[9] );
	//TransmitMessage((BYTE*)MESG,DEBUG_PORT);
	
    //MessageOut(MESG);
    lsiPrevTEMP_RAW_DIGITS=lsiTEMP_RAW_DIGITS;

}



/* kang
void ReadCounter1()
{
  unsigned short Char1, Char2, Char3, Char4, skew;
  unsigned short usSC[2];

  lsiTEMP_RAW_DIGITS = ReadMainCounterAll ();

  lsiTEMP_TRACE_RAW_DIGITS = ReadTraceCounterFPGA ();

  sprintf ((char *) MESG,
	   "%02X%02X"
	   "| %9d | %9d|[Trace] %9d"
	   "| %12.3f | %12.3f"
	   "| %2d:%2d:%2d"
	   "\r\n",
	   usSC[0], usSC[1],
	   lsiTEMP_RAW_DIGITS, lsiTEMP_RAW_DIGITS - lsiPrevTEMP_RAW_DIGITS,
	   lsiTEMP_TRACE_RAW_DIGITS, RAW_OFFSET, RAW_DIFFERENCE,
	   SYSTEM.TIME.CUR.HOUR, SYSTEM.TIME.CUR.MINUTE,
	   SYSTEM.TIME.CUR.SECOND);


	//sprintf((char*)MESG,"%d<+>Counter:%d : %d\r\n",iLsiDebugVariable,lsiTEMP_RAW_DIGITS,lsiTEMP_RAW_DIGITS-lsiPrevTEMP_RAW_DIGITS );

  MessageOut (MESG);
  lsiPrevTEMP_RAW_DIGITS = lsiTEMP_RAW_DIGITS;

}
kang */


int lsiPrevTraceTEMP_RAW_DIGITS;
int lsiTEMPTrace_RAW_DIGITS;

/* kang
void ReadTraceCounter()
{

  unsigned short Char1, Char2, Char3, Char4, skew;

  Char1 = *TraceCounterAddr1;
  Char2 = *TraceCounterAddr2;
  Char3 = *TraceCounterAddr3;
  Char4 = *TraceCounterAddr4;

    //lsiTEMPTrace_RAW_DIGITS=    Char1 & 0x000F;
    //lsiTEMPTrace_RAW_DIGITS+=   ((Char1 & 0x00F0) >> 4)   * 10;
    //lsiTEMPTrace_RAW_DIGITS+=   ( Char2 & 0x000F)         * 100;
    //lsiTEMPTrace_RAW_DIGITS+=   ((Char2 & 0x00F0) >> 4)   * 1000;
    //lsiTEMPTrace_RAW_DIGITS+=   ( Char3 & 0x000F)         * 10000;
    //lsiTEMPTrace_RAW_DIGITS+=   ((Char3 & 0x00F0) >> 4)   * 100000;
    //lsiTEMPTrace_RAW_DIGITS+=   ( Char4 & 0x000F)         * 1000000;
    //lsiTEMPTrace_RAW_DIGITS+=   ((Char4 & 0x00F0) >> 4)   * 10000000;

  lsiTEMPTrace_RAW_DIGITS = ReadMainCounterAll ();

  sprintf ((char *) MESG, "%d,TraceCounter:%d : %d\r\n", Char4 & 0x00F0 >> 4,
	   lsiTEMPTrace_RAW_DIGITS, (int) ReadTraceCounterFPGA ());
  MessageOut (MESG);
  lsiPrevTraceTEMP_RAW_DIGITS = lsiTEMPTrace_RAW_DIGITS;

}
kang */






void StartPLL()
{
//EnablePLL();
//EnablePLL2();
}



void ClearFail()
{

  //if( IsFailStatusHigh( M_BLOCK_MY_FAIL ) ){

  //if( iLsiClrBitCount++ < 5 ) return ;

  iLsiClrBitCount = 0;

  ClearYourFail();
  ClearMyFail();

//  SetStatusClrHigh (M_CLR_HW_FAIL);
//  SetStatusClrLow (M_CLR_HW_FAIL);

//  SetStatusClrHigh (M_CLR_DEBUG_BIT);
//  SetStatusClrLow (M_CLR_DEBUG_BIT);


//              SetStatusClrHigh( M_CLR_CLK_FAIL);
//              SetStatusClrLow( M_CLR_CLK_FAIL);
  //}

}



extern int SigOnValue;
void UnconditionalSigOn()
{

  	if (iLsiDebugVariable == 20 || iLsiDebugVariable == 21 || iLsiDebugVariable == 25 )    return;
  	
  	SetSigOnOffLow (M_ALLOW_DUAL_EVENT);	// Event Input
  	
  	SetSigOnOffHigh (M_EN_EVENT_ON_MY_FAIL | M_EN_EVENT_ON_YOUR_FAIL);
  	
  	SetSigOnOffLow (M_EVENT_CLK);
  	SetSigOnOffHigh (M_EVENT_CLK);	//( rising trigger )
  	
  	SetSigOnOffHigh (M_EN_SIG);	// Enable
  	
  	ClearFail();
  	
  	SetMeActive();
  	SetMeSwitchNotReady();
  	//SYSTEM_FAIL_OFF();
}

void UnconditionalSigOff()
{
	if( psda.my_priority_value==dpSigOn ) return ;
  	if (iLsiDebugVariable == 20 || iLsiDebugVariable == 21 || iLsiDebugVariable == 25 )    return;
  	
  	SetSigOnOffLow (M_ALLOW_DUAL_EVENT);	// Event Input;
  	
  	SetSigOnOffLow (M_EN_EVENT_ON_MY_FAIL | M_EN_EVENT_ON_YOUR_FAIL);
  	
  	SetSigOnOffLow (M_EVENT_CLK);
  	
  	SetSigOnOffHigh (M_EVENT_CLK);	//( rising trigger )
  	
  	
  	SetSigOnOffHigh (M_EN_SIG);
  	
  	ClearFail ();
  	
  	SetMeNotActive();
  	SetMeSwitchNotReady();
  	
  	SigOnValue = 0;
  	//SYSTEM_FAIL_ON();
}


int iModeManualSigOnOff = OFF;
void SigOnWithReadyOff()
{

	if ( iModeManualSigOnOff==ON )    return;
	
	SetSigOnOffLow (M_ALLOW_DUAL_EVENT);	// Event Input
	
	//1)MyFailData:1  YourFailData:1 Clocking => On
	
	SetSigOnOffHigh (M_EN_EVENT_ON_MY_FAIL | M_EN_EVENT_ON_YOUR_FAIL);
	SetSigOnOffLow (M_EVENT_CLK);
	SetSigOnOffHigh (M_EVENT_CLK);
	SetSigOnOffLow (M_EVENT_CLK);
	
	
	SetSigOnOffLow (M_EN_EVENT_ON_YOUR_FAIL);
	
	SetSigOnOffLow (M_EVENT_CLK);
	SetSigOnOffHigh (M_EVENT_CLK);
	SetSigOnOffLow (M_EVENT_CLK);
	
	//3)MyFail SigOnData1,2
	SetSigOnOffLow (M_EN_EVENT_ON_MY_FAIL);
	
	SetSigOnOffHigh (M_EN_SIG);	// Enable

  	SetSigOnOffHigh (M_ALLOW_DUAL_EVENT);
  	
  	//if( bLsiMonitorEnable ){ MessageOut(" SigOff");}
  	
  	//SYSTEM_FAIL_OFF();
  	
  	SetMeActive();
	SetMeSwitchReady();
  	
  	ClearFail();
  	
  	SigOnValue = 1;
}

void SigOffWithReadyOn()
{
	if( psda.my_priority_value==dpSigOn ) return ;
	if ( iModeManualSigOnOff==ON )    return;
	
	SetSigOnOffLow (M_ALLOW_DUAL_EVENT);
	
	//1)MyFailData:0  YourFailData:0 Clocking => Off
	
	SetSigOnOffLow (M_EN_EVENT_ON_MY_FAIL | M_EN_EVENT_ON_YOUR_FAIL);
	
	SetSigOnOffLow (M_EVENT_CLK);
	SetSigOnOffHigh (M_EVENT_CLK);
	SetSigOnOffLow (M_EVENT_CLK);
	
	
	SetSigOnOffHigh (M_EN_EVENT_ON_YOUR_FAIL);
	
	SetSigOnOffHigh (M_EN_SIG);
	
	SetSigOnOffHigh (M_ALLOW_DUAL_EVENT);
	
	SetMeNotActive();
	SetMeSwitchReady();
	//SYSTEM_FAIL_OFF();
	SigOnValue = 0 ;
}


void InitDualCondition()
{
/*
	SetMyStatusHigh(M_BLOCK|M_ACTIVE| M_STANDBY | M_BLOCKED  );
	SetDualStatusHigh( M_SELF_BLOCK );
	SetDualStatusLow(  M_ALLOW_SIG_ONOFF  ) ;  // disable
*/
}


void UnconditionalSigOn1()
{
  	iModeManualSigOnOff=ON ;
  	
  	SetSigOnOffLow (M_ALLOW_DUAL_EVENT);	// Event Input;
  	SetSigOnOffHigh (M_EN_EVENT_ON_MY_FAIL | M_EN_EVENT_ON_YOUR_FAIL);
  	
  	SetSigOnOffLow (M_EVENT_CLK);
  	SetSigOnOffHigh (M_EVENT_CLK);	//( rising trigger )
  	
  	SetSigOnOffHigh (M_EN_SIG);
  	
  	ClearFail ();
  	
  	SigOnValue = 0;
  	//SYSTEM_FAIL_ON();

}

void UnconditionalSigOff1 ()
{

	iModeManualSigOnOff=ON ;
  	SetSigOnOffLow (M_ALLOW_DUAL_EVENT);	// Event Input
  	
  	SetSigOnOffLow (M_EN_EVENT_ON_MY_FAIL | M_EN_EVENT_ON_YOUR_FAIL);
  	
  	SetSigOnOffLow (M_EVENT_CLK);
  	
  	SetSigOnOffHigh (M_EVENT_CLK);	//( rising trigger )
  	
  	SetSigOnOffHigh (M_EN_SIG);	// Enable
  	
  	ClearFail();
  	
  	SigOnValue = 1;
}



void SigOnWithReadyOff1 ()
{
	iModeManualSigOnOff=ON ;
  	SetSigOnOffLow (M_ALLOW_DUAL_EVENT);

  	SetSigOnOffHigh (M_EN_EVENT_ON_MY_FAIL | M_EN_EVENT_ON_YOUR_FAIL);
  	SetSigOnOffLow (M_EVENT_CLK);
  	SetSigOnOffHigh (M_EVENT_CLK);
  	SetSigOnOffLow (M_EVENT_CLK);
  	
  	SetSigOnOffLow (M_EN_EVENT_ON_YOUR_FAIL);
  	
  	SetSigOnOffLow (M_EVENT_CLK);
  	SetSigOnOffHigh (M_EVENT_CLK);
  	SetSigOnOffLow (M_EVENT_CLK);
  	
  	SetSigOnOffLow (M_EN_EVENT_ON_MY_FAIL);
  	
  	SetSigOnOffHigh (M_EN_SIG);
  	
  	SetSigOnOffHigh (M_ALLOW_DUAL_EVENT);

  	//if( bLsiMonitorEnable ){ MessageOut(" SigOff");}
  	
  	//SYSTEM_FAIL_OFF();

}

void SigOffWithReadyOn1()
{
	iModeManualSigOnOff=ON ;
  	SetSigOnOffLow (M_ALLOW_DUAL_EVENT);
  	
  	SetSigOnOffLow (M_EN_EVENT_ON_MY_FAIL | M_EN_EVENT_ON_YOUR_FAIL);
  	
  	SetSigOnOffLow (M_EVENT_CLK);
  	SetSigOnOffHigh (M_EVENT_CLK);
  	SetSigOnOffLow (M_EVENT_CLK);
  	
  	SetSigOnOffHigh (M_EN_EVENT_ON_YOUR_FAIL);
  	
  	SetSigOnOffHigh (M_EN_SIG);
  	
  	SetSigOnOffHigh (M_ALLOW_DUAL_EVENT);
  	
  	//SYSTEM_FAIL_OFF();
}


unsigned short usADCValue, usADCU_Detail500ns, usADCU_Detail50ns, ReferenceADC, usADCVcxo, usADCDetail;



float fPlus5V=0, fPlusVcc=0, fMinusVee=0, fVCXOEfc=0;
// ADC 400kHZ Max Clock


//-------------------------------------------------------------------------------------------------------------
#define GetCount1st(x)		GetFpgaValue(x+3)
#define GetCount2nd(x)		( (GetFpgaValue(x+2)&(~0x3))>>2 )
#define GetCount3rd(x)		( ( (GetFpgaValue(x+2)&0x3)<<16) + (GetFpgaValue(x+1)<<8) + (GetFpgaValue(x)) )
//-------------------------------------------------------------------------------------------------------------
//kang ---> Detail Counter : using FPGA Counter
float g_detail;
int detail_cnt;
void MonitorADCValue( int usChannel )
{
    unsigned short usTmpADCValue = 0;
	float TmpDetailValue = 0;
	
	unsigned int nXs = 0;
	unsigned int n100s = 0;
	
	nXs = GetFpgaValue(13)&0x7F;

	//n100s = GetFpgaValue(14)&0x7F;
	n100s = 32;
	
	//printf("nXs:%d,",nXs);
	
	detail_cnt = nXs - n100s;
	
	detail_cnt = max( detail_cnt, 0);
	detail_cnt = min( detail_cnt, n100s*2);
	
	//printf("detail_cnt:%d, ",detail_cnt);

	TmpDetailValue = (-1/(double)n100s)*(detail_cnt) + 0.5;
//	TmpDetailValue = (-1/(double)n100s)*(detail_cnt) + 0.2;	//sewon	120601
	g_detail = TmpDetailValue;
	
	//printf("Detail Value:%f\n", TmpDetailValue);
//printf("[ADC:%d,%d,%.2f]",nXs,detail_cnt,TmpDetailValue);
	//usTmpADCValue = ioctl(fdFPGA, IOCTL_ADC_GET_VAL, 0);
	//printf("ADC : %d\n", usTmpADCValue);	
	
	switch (usChannel)
	{
		case ADC_NEW_DETAIL_CHANNEL50NS:
      		//kang usADCDetail = TmpDetailValue;
      		break;
			
		case ADC_VCXO_EFC_CHANNEL:
      		//fVCXOEfc = VREF*(  (float)TmpDetailValue/(float)ADC_MAX_VALUE );
      		fVCXOEfc = 0;
      		break;
			
		case ADC_PLUS_VCC_CHANNEL:
			//kang fPlusVcc = VCC_MULTIPLY_VALUE * VREF * ((float) usTmpADCValue / (float) ADC_MAX_VALUE);
      		//fPlusVcc=0;
      		break;
			
		default:
			break;

    }

}




void emac_show_regs(void)
{
int regs[16];

	regs[0]=ioctl(fdFPGA, IOCTL_SHOW_EMAC_REGS, EMAC_FCSE_OFFSET);
	regs[1]=ioctl(fdFPGA, IOCTL_SHOW_EMAC_REGS, EMAC_ALE_OFFSET);
	regs[2]=ioctl(fdFPGA, IOCTL_SHOW_EMAC_REGS, EMAC_LCOL_OFFSET);
	regs[3]=ioctl(fdFPGA, IOCTL_SHOW_EMAC_REGS, EMAC_RRE_OFFSET);
	regs[4]=ioctl(fdFPGA, IOCTL_SHOW_EMAC_REGS, EMAC_ROV_OFFSET);
	regs[5]=ioctl(fdFPGA, IOCTL_SHOW_EMAC_REGS, EMAC_RSE_OFFSET);
	regs[6]=ioctl(fdFPGA, IOCTL_SHOW_EMAC_REGS, EMAC_ELE_OFFSET);
	regs[7]=ioctl(fdFPGA, IOCTL_SHOW_EMAC_REGS, EMAC_RJA_OFFSET);
	regs[8]=ioctl(fdFPGA, IOCTL_SHOW_EMAC_REGS, EMAC_USF_OFFSET);
	regs[9]=ioctl(fdFPGA, IOCTL_SHOW_EMAC_REGS, EMAC_RLE_OFFSET);
	
	regs[10]=ioctl(fdFPGA, IOCTL_SHOW_EMAC_REGS, EMAC_NCR_OFFSET);
	regs[11]=ioctl(fdFPGA, IOCTL_SHOW_EMAC_REGS, EMAC_NCFGR_OFFSET);
	
	regs[12]=ioctl(fdFPGA, IOCTL_SHOW_EMAC_REGS, EMAC_FRO_OFFSET);
	regs[13]=ioctl(fdFPGA, IOCTL_SHOW_EMAC_REGS, EMAC_FTO_OFFSET);

	printf("\nFCSE: 0x%.04x   ALE : 0x%.04x   LCOL: 0x%.04x   RRE : 0x%.04x\n",
		regs[0],regs[1],regs[2],regs[3]);
	printf("ROV : 0x%.04x   RSE : 0x%.04x   ELE : 0x%.04x   RJA : 0x%.04x\n",
		regs[4],regs[5],regs[6],regs[7]);
	printf("USF : 0x%.04x   RLE : 0x%.04x   NCR : 0x%.04x   NCFG: 0x%.04x\n",
		regs[8],regs[9],regs[10],regs[11]);
	printf("FRO : 0x%.04x   TFO : 0x%.04x\n",
		regs[12],regs[13]);
}

#include <net/if.h>
struct mii_data {
    unsigned short	phy_id;
    unsigned short	reg_num;
    unsigned short	val_in;
    unsigned short	val_out;
};

int skfd = -1;
struct ifreq ifr;

int mdio_read(int skfd, int location);
void mdio_write(int skfd, int location, int value);


int phy_get_regs(int offset )
{
int v;

	if ((skfd = socket(AF_INET, SOCK_DGRAM,0)) < 0) {
		printf("socket error\n");
		return 0;
    }
    strncpy(ifr.ifr_name, "eth0", IFNAMSIZ);
	v = mdio_read(skfd, offset);
    close(skfd);
    return v;
}

int mdio_read(int skfd, int location)
{
struct mii_data *mii = (struct mii_data *)&ifr.ifr_data;

	if((location & ~0x8000) > PHY_PAGESEL){
        // Make sure correct register page is selected
        if((mdio_read(skfd, PHY_PAGESEL) & 0x07) != (((location & 0x00E0) >> 5) & 0x07)){
        	mdio_write(skfd, (PHY_PAGESEL | (location & 0x8000)), (location & 0x00E0) >> 5);
        }
        location &= ~0xE0;
    }
    
    mii->reg_num = location;
    if (ioctl(skfd, SIOCGMIIREG, &ifr) < 0) {
		printf("SIOCGMIIREG on %s failed: %s\n", ifr.ifr_name,strerror(errno));
		return -1;
    }
    return mii->val_out;
}


void mdio_write(int skfd, int location, int value)
{
struct mii_data *mii = (struct mii_data *)&ifr.ifr_data;

	if((location& ~0x8000) > PHY_PAGESEL){
        // Make sure correct register page is selected
        if((mdio_read(skfd,PHY_PAGESEL) & 0x07) != (((location & 0x00E0) >> 5) & 0x07)){
        	mdio_write(skfd, (PHY_PAGESEL | (location & 0x8000)), (location & 0x00E0) >> 5);
        }
        location &= ~0xE0;
        // Preamble has been taken care of by the write operation
    }
    
    mii->reg_num = location;
    mii->val_in = value;
    if (ioctl(skfd, SIOCSMIIREG, &ifr) < 0) {
		printf("SIOCSMIIREG on %s failed: %s\n", ifr.ifr_name,strerror(errno));
    }
}


void phy_show_regs(void)
{
int fcscr, recr, len100t, freq100;
	
	if ((skfd = socket(AF_INET, SOCK_DGRAM,0)) < 0) {
		printf("socket error\n");
		return;
    }
    
    strncpy(ifr.ifr_name, "eth0", IFNAMSIZ);

	fcscr = mdio_read(skfd, PHY_FCSCR);
	recr = mdio_read(skfd, PHY_RECR);
	len100t = mdio_read(skfd, DP83640_PHY_PG2_LEN100_DET);
	freq100 = mdio_read(skfd, DP83640_PHY_PG2_FREQ100);
	
	
    printf("\nFCSCR: 0x%.04x   RECR : 0x%.04x   LEN  : 0x%.04x   FREQ : 0x%.04x\n", 
    	fcscr,recr,len100t,freq100);
    
    close(skfd);
}

void Lsi00sec()
{

}


char start_unlock = 0;
char eb_tdebug = 0;
char slope_debug = 0;

int OCXOAgingIndex = 0;

int SelMonitorStatusDebug = 0;
int debug_out_udp = 0;    //
char debug_calc=0;
extern void grca_issue_gps_req(void);
char no_system_fail = 0;
char temp_sensor_debug = 0;
int debug_send_local = 0;
int config_debug=0;
int log_debug = 0;
int dual_fail_debug = 0;
int dual_clear_debug = 0;
int wdt_debug = 0;
int temp_debug = 0;
int dual_rx_debug = 0;
int dual_tx_debug = 0;
void Lsi01sec ()
{
  unsigned char *addr = (unsigned char *)(0x2000000);

  unsigned short YSA;
  unsigned short AdcTmp[5];
  int i;
  float e1_ma,e2_ma;
  char d1,d2;
  int t1,t2,t3,t4;
  double f1,f2,f3,f4;
  
  
  double Aging_x[800];
  double Aging_Intercept, Aging_Slope;

  switch (iLsiDebugVariable)
    {


    case 1:
      ReadCounter();
      break;

    case 2:
      //ReadTraceCounter();
      break;
	case 3:
		break;

	case 4: //OCXO-ID Table ���
		break;
	
	case 5: //OCXO Aging Table ��� ����
		break;
	case 6: //OCXO Aging Table ��� ����

		break;		

	case 7: //OCXO Aging Table ��� ����
		
		//fwup_debug_tftp_start();
		printf("fw_debug tftp start\n");
		iLsiDebugVariable = 0;
		break;
	
	case 8: //OCXO Aging Table ��� ����
		printf("fw_debug download start\n");
		
		//fwup_debug_fwdownload_start();
		iLsiDebugVariable = 0;
		break;	
	
	case 9: //OCXO Aging Table ��� ����
		
		temp_sensor_debug = !temp_sensor_debug;
		printf("temp sensor debug:%d\n",temp_sensor_debug);
		iLsiDebugVariable = 0;
		break;	
		
	case 10:
      printf("FAN1:%d, FAN2:%d\n", QueryFANALM1(), QueryFANALM2() );
      iLsiDebugVariable = 0;
      break;

    
    case 11:
    	TOD.printon = ON;
    	iLsiDebugVariable = 0;
      	break;
     	
    case 12:
    	TOD.printon = OFF;
    	iLsiDebugVariable = 0;
      	break;

	case 13:
    	printf("restart temp sensor\n");
    	ioctl(fdFPGA, IOCTL_TEMP_RESET, 0);
    	
    	iLsiDebugVariable = 0;
      	break;
    
    case 14:
    	backup_copy_log();
		iLsiDebugVariable = 0;
    	break;
    	
    case 15:
    	printf("version request start\n");
    	//fwup_debug_version_request();
		iLsiDebugVariable = 0;
    	break;	
    case 16:
    	printf("sync request start\n");
    	//fwup_debug_sync_request();
    	iLsiDebugVariable = 0;
    	break;
    case 17:
    	debug_send_local = !debug_send_local;
    	printf("debug send 118.220.36.x: %d\n",debug_send_local);
    	iLsiDebugVariable = 0;
    	break;
    case 18:
    	CONFIG.WriteEvent = ON;
    	printf("CONFIG.WriteEvent ON\n");
    	iLsiDebugVariable = 0;
    	break;
    case 19:
    	config_debug = !config_debug;
    	printf("config_debug %d\n",config_debug);
    	iLsiDebugVariable = 0;
    	break;

    case 20:
      	printf("before SigOn Result:%d<<20\n",IsSigOn());
	  	UnconditionalSigOn1 ();
      	printf("after  SigOn Result:%d\n",IsSigOn());
      	iLsiDebugVariable = 25;
      	break;
    case 21:
      	printf("before SigOn Result:%d<<21\n",IsSigOn());
      	UnconditionalSigOff1 ();
      	printf("after  SigOn Result:%d\n",IsSigOn());
      	iLsiDebugVariable = 25;
      	break;
    case 22:
      	printf("before SigOn Result:%d<<22\n",IsSigOn());
      	SigOnWithReadyOff1 ();
      	printf("after  SigOn Result:%d\n",IsSigOn());
      	iLsiDebugVariable = 0;
      	break;
    case 23:
      	printf("before SigOn Result:%d<<23\n",IsSigOn());
      	SigOffWithReadyOn1 ();
      	printf("after  SigOn Result:%d\n",IsSigOn());
      	iLsiDebugVariable = 0;
      	break;

    case 24:
      	//printf("before SigOn Result:%d<<23\n",IsSigOn());
	  	printf("iModeManualSigOnOff=OFF\n");
	  	iModeManualSigOnOff=OFF;
      	iLsiDebugVariable = 0;	
      	break;

	case 25:
      	//printf("before SigOn Result:%d<<23\n",IsSigOn());
      	if(SYSTEM.ID == ModuleA){
      		if(((SYSTEM.OPERATION.OPMODE == OPMODE_POWERUP) || (SYSTEM.OPERATION.OPMODE == OPMODE_WARMUP)) ||
      			((CounterModule.LockMode == 0x00) && (CounterModule.EXIST == YES)))
      		{
      			DIAG.DUAL_TEST = UNDEFINED;
      			dual_test_start = YES;
	  			//DIAG.DUAL_STEP = TRY_TESTMODE;
	  			dual_test_retry = 0;
	  			DIAG.DUAL_TIMEOUT = 0;
	  			printf("Dual channel test start\n");
	  		}
	  		else{
	  			printf("Dual channel test not available %d,%d\n", SYSTEM.OPERATION.OPMODE, CounterModule.LockMode);
	  		}
	  	}
	  	else{
	  		printf("Dual channel test error - Only for A side\n");
	  	}
      	iLsiDebugVariable = 0;	
      	break;
     
    case 26:
      	//printf("before SigOn Result:%d<<23\n",IsSigOn());
	  	SetDualTxModeToTest();
	  	SetDualTxModeToOperation();
      	iLsiDebugVariable = 0;	
      	break;
	case 27:
      	//printf("before SigOn Result:%d<<23\n",IsSigOn());
	  	SetDualTxModeToTest();
      	iLsiDebugVariable = 0;	
      	break;
	case 28:
      	//printf("before SigOn Result:%d<<23\n",IsSigOn());
	  	SetDualTxModeToOperation();
      	iLsiDebugVariable = 0;	
      	break;
    
    case 29:
    	SetDualTxValueToHigh();
    	iLsiDebugVariable = 0;	
      	break;
      
    case 30:
      	//CONTROL.SYNC = ON;
    	//sewon 12-07-13
        if(VME.Data.TimeSync_Mode!=VME_ExtClock_MODE)	Clear1PPSwithGPS();
        else											Clear1PPSwithGPS_Ext1pps();
      	iLsiDebugVariable = 0;
      	break;
    case 31:
      	CONTROL.TRACE_SYNC = ON;
      	iLsiDebugVariable = 0;
      	break;
	case 32:
      	log_debug = !log_debug;
      	printf("log_debug %d\n",log_debug);
      	iLsiDebugVariable = 0;
      	break;

	case 33:
		//inv_debug_request();
		iLsiDebugVariable = 0;	
      	break;
    case 34:
		dual_fail_debug = !dual_fail_debug;
		printf("dual fail mode %d\n",dual_fail_debug);
		iLsiDebugVariable = 0;	
      	break;  	
    case 35:
		dual_clear_debug = !dual_clear_debug;
		printf("dual don't clear %d\n",dual_clear_debug);
		iLsiDebugVariable = 0;	
      	break;
    case 36:
		dual_rx_debug = !dual_rx_debug;
		printf("dual rx debug %d\n",dual_rx_debug);
		iLsiDebugVariable = 0;	
      	break;
	case 37:
		dual_tx_debug = !dual_tx_debug;
		printf("dual tx debug %d\n",dual_tx_debug);
		iLsiDebugVariable = 0;	
      	break;
	case 39:
    	SetDualTxValueToLow();
    	iLsiDebugVariable = 0;	
      	break;  	
    case 40:
      	SelMonitorStatusDebug = 0;
      	printf("\r\n===>MonitorSTATUS();\n");
      	iLsiDebugVariable = 0;
      	break;

    case 41:
    	SelMonitorStatusDebug = 1;
    	printf("\r\n===>MyMonitorSTATUSForDebug();\n");
      	iLsiDebugVariable = 0;
     	break;
    case 42:
    	wdt_debug = !wdt_debug;
    	printf("\r\nWDT DEBUG:%d\n",wdt_debug);
      	iLsiDebugVariable = 0;
     	break;	
    case 43:
    	temp_debug = !temp_debug;
    	printf("\r\nTEMP_DEBUG:%d\n",temp_debug);
    	iLsiDebugVariable = 0;
     	break;	
	case 50:
		debug_out_udp = !debug_out_udp;
		printf("UDP debug print %d\n", debug_out_udp);
		iLsiDebugVariable = 0;
     	break;
   
    case 51:
		//grca_issue_gps_req();
		//iLsiDebugVariable = 0;
     	break; 
    case 52:
    	//grca_issue_ka_req();
    	//iLsiDebugVariable = 0;
     	break; 
    case 60:
    	emac_show_regs();
    	iLsiDebugVariable = 0;
     	break; 
     
	case 61:
		phy_show_regs();
		iLsiDebugVariable = 0;
     	break; 
     
    case 75:

      MonitorPlusVcc ();

      sprintf ((char *) MESG,
	       "Detail: %4d Vcc:%4.2f Max:%d,Center:%d\r\n",
	       usADCDetail,fPlusVcc,(int)usMaxADC,(int)usCenterADC);

/*			sprintf((char*)MESG,"ADC: %4d Vdig:%4.2f Vcc:%4.2f Vee:%4.2f  Vcxo:%4.2f \r\n",
								usADCValue,fPlus5V,fPlusVcc,fMinusVee,fVCXOEfc );
*/
      TransmitMessage ((BYTE *) MESG, DEBUG_PORT);

      
      break;


//kang---------------------------------------
    case 100:
		OCXOID.TraceControl = ON;
		//iLsiDebugVariable = 0;
    	break;

    case 101:
		OCXOID.TraceControl = OFF;
		//iLsiDebugVariable = 0;
    	break;

	case 102:
		UnconditionalSigOff1();
		SelectExt1PPSRef();
		iLsiDebugVariable = 100;
		OCXOID.step = 0	;
    	break;

    case 103:
		//UnconditionalSigOn1();
		SigOffWithReadyOn1();
		
		DeSelectExt1PPSRef();
		iLsiDebugVariable = 101;
    	break;
//kang---------------------------------------
	case 160:
		TransmitMessage((BYTE*)"START CALC\r\n",DEBUG_PORT);
		debug_calc = 1;
    	iLsiDebugVariable=0;
		break;
		
    case 161:
		/*kang
		sprintf ((char *) MESG,
	    	"Detail: %4d(%d) Vcc:%4.2f Max:%d,Center:%d, Freq:%+.2E(%d, %d), TRO:%d, RO:%d, WC:%d\r\n",
	       	usADCDetail, ssDetailTable[usADCDetail], fPlusVcc,(int)usMaxADC,(int)usCenterADC, 
	       	CONTROL.Frequency, freq_stable_cnt,freq_stable_enough, 
	       	(int)TEMP_RAW_DIGITS, (int)RAW_OFFSET, waiting_change_eb);

		TransmitMessage ((BYTE *) MESG, DEBUG_PORT);
		*/
		break;
	case 163:
		TransmitMessage((BYTE*)"Start Traim query\r\n",DEBUG_PORT);
		start_traim_query = TRAIM_QUERY_ING;
		iLsiDebugVariable=0;
		break;
	case 167:
		TransmitMessage((BYTE*)"Enable Recevier 1PPS\r\n",DEBUG_PORT);
		traim_1pps(ENABLE);
		iLsiDebugVariable=0;
		break;
	case 168:
		TransmitMessage((BYTE*)"Disable Recevier 1PPS\r\n",DEBUG_PORT);
		traim_1pps(DISABLE);
		iLsiDebugVariable=0;
		break;
		
		
	//������� Holdover ��Ű��------------------------------------------------
	case 200:
			start_unlock = 1;
			TransmitMessage((BYTE*)"\r\nUNLOCK START\r\n",DEBUG_PORT);
	   		iLsiDebugVariable = 0;
		break;
		
	case 201:
			start_unlock = 0;
			TransmitMessage((BYTE*)"\r\nUNLOCK STOP\r\n",DEBUG_PORT);
	   		iLsiDebugVariable = 0;
		break;
	//-----------------------------------------------------------------------
	case 300:
		printf("tcflush ttyS1\n");
		tcflush(fdDUAL, TCIFLUSH);
		iLsiDebugVariable = 0;
		break;
	case 301:
		printf("reset ttyS1\n");
//		set_tty( fdDUAL, B57600, 2 );//sewon
		iLsiDebugVariable = 0;
		break;
	case 302:
		printf("close and reopen ttyS1\n");
		close(fdDUAL);
//		fdDUAL = open( name_Port_DUAL, O_RDWR | O_NOCTTY | O_NONBLOCK );
		if(fdDUAL<0){
			sprintf(MESG,"Port Reopen Fail: %s", strerror(errno));
    		LogItString(LOG_CATA1_NORM, LOG_CATA2_NOTHING, MESG);
			printf( "ttyS1 Open Error ...:%s\n",strerror(errno));
		}
		else{
			set_tty( fdDUAL, B57600, 2 );
		}
		iLsiDebugVariable = 0;
		break;
	
	case 303:
		debug_trace = !debug_trace;
		iLsiDebugVariable = 0;
		break;
	
	case 400:
		SelTodFPGA();
		printf("SelTodFPGA\n");
		iLsiDebugVariable = 0;
		break;
	case 401:
		WriteTODDataFPGA('x');
		WriteTODDataFPGA('y');
		printf("WriteTODDataFPGA\n");
		iLsiDebugVariable = 0;
		break;	
	case 402:
		WriteTODDataFPGA('x');
		WriteTODDataFPGA('y');
		printf("WriteTODDataFPGA\n");
		iLsiDebugVariable = 0;
		break;

	case 405:
		Sel_10MHz_Dual();
		printf("Sel_10MHz_Dual\n");
		iLsiDebugVariable = 0;
		break;	
	case 406:
		Sel_IntOsc_Dual();
		printf("Sel_IntOsc_Dual\n");
		iLsiDebugVariable = 0;
		break;	
	case 510:
		PrintON = !PrintON;
		printf("\r\n"
				"Print ON/OFF**********\n");
				
		iLsiDebugVariable = 0;		
      	break;

	case 600:
		SetRCUFuncFail();
		SetRCUClkFail();
		printf("\r\n" "Set Fail\n");
		iLsiDebugVariable = 0;
      	break;

	case 601:
		ResetRCUFuncFail();
		ResetRCUClkFail();
		printf("\r\n" "Reset Fail\n");
		iLsiDebugVariable = 0;
      	break;

	case 29999:
		Select1PPSOutwithEB();
	   	TransmitMessage((BYTE *) "\r\nSelect1PPSOutwithEB", DEBUG_PORT);
	   	iLsiDebugVariable = 0;
		break;
	case 30001:
		DeSelect1PPSOutwithEB();
	   	TransmitMessage((BYTE *) "\r\nDeSelect1PPSOutwithEB", DEBUG_PORT);
	   	iLsiDebugVariable = 0;
		break;
	case 30002:
		time_debug = 1;
	   	iLsiDebugVariable = 0;
		break;

	case 30003:
		time_debug = 0;
	   	iLsiDebugVariable = 0;
		break;

	//case 30004, 5:

    default:
      break;
    }

}



void Lsi02sec()
{

}

void Lsi05sec()
{
  if (iLsiDebugVariable == 5)
    {
      return;
    }
}


void Lsi10sec()
{



}


void Lsi15sec()
{

}


void Lsi20sec()
{

}


void Lsi30sec()
{

}


void Lsi300sec()
{


}


//End LSI
unsigned short usLsiCounter;


void
LsiTest()
{
  if (GC.Second < 3)
    {
      usLsiCounter = 0;
    }

  if (iLsiDebugVariable == 0 && !bLsiMonitorEnable)
    return;

  usLsiCounter++;


  Lsi01sec ();

  if (usLsiCounter == 0)
    Lsi00sec ();
  if ((usLsiCounter % 300) == 0)
    Lsi300sec ();

  if (usLsiCounter % 2 == 0)
    Lsi02sec ();

  if ((usLsiCounter % 5) == 0)
    Lsi05sec ();

  if ((usLsiCounter % 10) == 0)
    Lsi10sec ();

  if ((usLsiCounter % 15) == 0)
    Lsi15sec ();

  if ((usLsiCounter % 20) == 0)
    Lsi20sec ();

  if ((usLsiCounter % 30) == 0)
    Lsi30sec ();

  if ((usLsiCounter % 300) == 0)
    Lsi300sec ();

  if (usLsiCounter > 300)
    usLsiCounter = 0;

}


